<template>
  <div class="login-box" v-loading="isLoadingFlag">
    <Top></Top>
    <el-form class="login" ref="formRef" :model="form" label-width="60px">
      <div class="title">客服聊天工具 登录</div>
      <el-form-item label="用户名" class="item">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" class="item">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code" v-if="captchaOnOff" class="item">
        <el-input
          v-model="form.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
        >
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>
      <el-form-item label="主机" class="item">
        <el-input v-model="form.host" @blur="flush()">
          <template #append>
            <el-button @click="flush()">刷新</el-button>
          </template>
        </el-input>
      </el-form-item>
      <div class="el-row">
        <div class="el-col-12">
          <el-button type="info" @click="router.push('/register')"
            >注册</el-button
          >
        </div>
        <div class="el-col-12">
          <div class="text-right">
            <el-button type="primary" @click="submit">登录</el-button>
            <el-button>取消</el-button>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import Auth from "@/api/Auth";
import { useUserStore } from "@/store/userStore";
import { useChatStore } from "@/store/chatStore";
import UserApi from "@/api/UserApi";
import { getCodeImg, login, getWsUrl } from "@/api/Login";
import Top from "@/components/Top.vue";
import VimConfig from "@/config/VimConfig";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const chatStore = useChatStore();

const form = reactive({
  name: "",
  password: "",
  code: "",
  uuid: "",
  host: VimConfig.host,
});
const routerObj = ref();

// onMounted(() => {});
console.log("router,route", route);

const submit = () => {
  // const reg =
  //   /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
  // if (!reg.test(form.host)) {
  //   ElMessage.error("主机地址不对");
  //   return;
  // }
  // Auth.setIp(form.host);
  // http://localhost:8888/#/login?userName=wangzq&userid=24080610060110852153427502505985&dskey=fbank&token=eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoiMjQwODA2MTAwNjAxMTA4NTIxNTM0Mjc1MDI1MDU5ODUiLCJ1c2VyX2tleSI6IjI3Y2M3M2U3LTQ4MmYtNDg1Yy04ZThhLTk4ZjIwZWEwNjgyNyIsInVzZXJuYW1lIjoid2FuZ3pxIn0.-3WpzAJb1BjxFuvuChwFkok1F02QElkZHr9vOB1tGwK0U8uIqyRNiNj4lUnS9LSFyqM8qoZAVxiIt6H6EwhsKw
  const uerName = route.query.userName;

  const userid = route.query.userid;
  const user = {
    id: userid,
    name: uerName,
    avatar:
      userCC.value?.avatar ||
      "https://i.gtimg.cn/club/item/face/img/2/15922_100.gif",
  };
  console.log("user_123", user);

  userStore.storeUser(user.id, {
    name: uerName,
    avatar: user.avatar,
  });
  userStore.setUser(user);

  chatStore.reloadChats();
  router.push("/index/chat");
  // login(form.name, form.password, form.code, form.uuid)
  //   .then((res: any) => {
  //     Auth.setToken(res.token);
  //     return UserApi.currentUser();
  //   })
  //   .then((res) => {
  //     const user = res.data;
  //     userStore.storeUser(user.userId, { name: user.userName, avatar: user.avatar });
  //     userStore.setUser(user);
  //     chatStore.reloadChats();
  //     router.push("/index/chat");
  //   });
};

// 验证码开关
const captchaOnOff = ref(true);
const codeUrl = ref("");

const getCode = () => {
  // Auth.setIp("172.16.3.83");
  // getCodeImg().then((res: any) => {
  //   Auth.setIp(form.host);
  //   captchaOnOff.value =
  //     res.captchaOnOff === undefined ? true : res.captchaOnOff;
  //   if (captchaOnOff.value) {
  //     codeUrl.value = "data:image/gif;base64," + res.img;
  //     form.uuid = res.uuid;
  //   }
  // });
};

/**
 * 刷新主机
 */
const flush = () => {
  Auth.setIp(form.host);
  getCode();
};
const isLoadingFlag = ref(true);
onMounted(async () => {
  console.log("onMounted ——————1111");
  const token = route.query.token;
  Auth.setToken(token);
  const dskey = route.query.dskey;
  Auth.setLocal("dskey", dskey);
  Auth.isLogin()
    .then((res) => {
      if (res) {
        console.log("登录成功了", res);
        // router.push("/index/chat");
      }
    })
    .catch((err) => {
      console.error(err);
    });
  await getUsers();
  await getWSURLFun();
  form.host = Auth.getIp();
  setTimeout(() => {
    submit();
  }, 500);
});
const userCC = ref();
const getUsers = async () => {
  const userid = route.query.userid;
  console.log("getUser2", userid);

  await UserApi.getUser(userid).then((res) => {
    console.log("getUser", res.data);
    userCC.value = res.data;
  });
};
const getWSURLFun = async () => {
  await getWsUrl().then((res: any) => {
    console.log("sys_chat_ws_url", res);
    VimConfig.wsPort = res.msg;
    Auth.setLocal("wsPortUrl", res.msg);
  });
};
</script>

<style scoped lang="scss">
.login-box {
  background: url("../assets/bg.png") no-repeat;
  background-size: 100% 100%;
  height: 100%;
  box-shadow: #cccccc 10px 10px 10px;

  .logo-box {
    display: flex;
    justify-content: center;
    text-align: center;

    .logo {
      width: 15rem;
      height: 100%;
    }
  }

  .login {
    width: 50rem;
    margin: 10rem auto;
    background-color: rgba(#fff, 0.5);
    padding: 30px;

    .title {
      padding: 15px;
      text-align: center;
      font-size: 2rem;
      color: #5fb878;
    }
  }

  .login-code {
    flex: 1;
    height: 32px;

    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
